<!-- 资源管理 -->
<script setup lang="tsx">
import { reactive, ref, unref } from 'vue'
import { getMenuListApi, sysResourceSaveOrUpdate, sysResourceDeleteById } from '@/api/backstage'
import { useTable } from '@/hooks/web/useTable'
import { useI18n } from '@/hooks/web/useI18n'
import { Table, TableColumn } from '@/components/Table'
import { ElTag } from 'element-plus'
import { Icon } from '@/components/Icon'
import { Search } from '@/components/Search'
import { ElTree } from 'element-plus'
import { FormSchema } from '@/components/Form'
import { ContentWrap } from '@/components/ContentWrap'
import { Write, Detail, clientTypeTreeData } from './components'
import { Dialog } from '@/components/Dialog'
import { BaseButton } from '@/components/Button'

const { t } = useI18n()

const { tableRegister, tableState, tableMethods } = useTable({
  fetchDataApi: async () => {
    const res = await getMenuListApi(unref(searchParams))
    return {
      list: res.data || []
    }
  },
  fetchDelApi: async () => {
    const res = await sysResourceDeleteById({ id: unref(delId) })
    return !!res
  }
})

const { dataList, loading } = tableState

const { getList, delList } = tableMethods
const tableColumns = reactive<TableColumn[]>([
  {
    field: 'index',
    label: t('userDemo.index'),
    type: 'index'
  },
  {
    field: 'name',
    label: t('menu.menuName'),
    width: 200,
    slots: {
      default: (data: any) => {
        return <>{data.row.name}</>
      }
    }
  },
  {
    field: 'type',
    label: '菜单类型',
    slots: {
      default: (data) => {
        const type = data.row.type
        return <>{['菜单', '目录', '按钮链接'][type]}</>
      }
    }
  },
  {
    field: 'clientType',
    label: '客户端类型',
    width: 100,
    slots: {
      default: (data) => {
        const clientType = data.row.clientType
        return <>{['PC端', '手机端'][clientType]}</>
      }
    }
  },
  {
    field: 'menuPosition',
    label: '菜单位置',
    slots: {
      default: (data) => {
        const menuPosition = data.row.menuPosition
        return <>{['左侧导航', '顶部菜单', '其他位置'][menuPosition]}</>
      }
    }
  },
  // {
  //   field: 'meta.icon',
  //   label: t('menu.icon'),
  //   slots: {
  //     default: (data: any) => {
  //       const icon = data.row.meta.icon
  //       if (icon) {
  //         return (
  //           <>
  //             <Icon icon={icon} />
  //           </>
  //         )
  //       } else {
  //         return null
  //       }
  //     }
  //   }
  // },
  // {
  //   field: 'meta.permission',
  //   label: t('menu.permission'),
  //   slots: {
  //     default: (data: any) => {
  //       const permission = data.row.meta.permission
  //       return permission ? <>{permission.join(', ')}</> : null
  //     }
  //   }
  // },
  {
    field: 'routeWay',
    label: '路由地址'
  },
  {
    field: 'routePath',
    label: '组件路径',
    slots: {
      default: (data: any) => {
        const component = data.row.routePath
        return <>{component}</>
      }
    }
  },
  {
    field: 'redirect',
    label: '重定向'
  },
  {
    field: 'sortOrder',
    label: '排序号'
  },
  {
    field: 'status',
    label: t('menu.status'),
    slots: {
      default: (data: any) => {
        return (
          <>
            <ElTag type={data.row.status === 0 ? 'success' : 'danger'}>
              {data.row.status === 1 ? '停用' : '正常'}
            </ElTag>
          </>
        )
      }
    }
  },
  {
    field: 'show',
    label: '显示',
    slots: {
      default: (data: any) => {
        return (
          <>
            <ElTag type={data.row.show === 0 ? 'success' : 'danger'}>
              {data.row.show === 1 ? '隐藏' : '显示'}
            </ElTag>
          </>
        )
      }
    }
  },
  {
    field: 'outside',
    label: '是否外链',
    slots: {
      default: (data: any) => {
        return <>{data.row.outside === 1 ? '是' : '否'}</>
      }
    }
  },
  {
    field: 'action',
    label: t('userDemo.action'),
    width: 200,
    slots: {
      default: (data: any) => {
        const row = data.row
        return (
          <>
            <BaseButton type="primary" link onClick={() => action(row, 'edit')}>
              {t('exampleDemo.edit')}
            </BaseButton>
            <BaseButton type="success" link onClick={() => action(row, 'detail')}>
              {t('exampleDemo.detail')}
            </BaseButton>
            <BaseButton type="danger" link onClick={() => delData(row)}>
              {t('exampleDemo.del')}
            </BaseButton>
          </>
        )
      }
    }
  }
])

const delLoading = ref(false)
const delId = ref('')
const delData = async (row?: any) => {
  delId.value = row.id

  delLoading.value = true

  await delList(1).finally(() => {
    delLoading.value = false
  })
}

const treeProps = {
  children: 'children',
  label: 'label',
  value: 'id'
}
const ElTreeRef = ref()
setTimeout(() => {
  ElTreeRef.value!.setCurrentKey(0)
}, 100)

const handleNodeClick = (data: any) => {
  console.log('Node clicked:', data)
  if (data.id === 999) return
  searchParams.value.clientType = data.id
  console.log('searchParams', ElTreeRef.value!.getCurrentKey())

  getList()
}
const searchParams = ref({
  clientType: 0,

  name: '',
  status: null
})

const initValue = (Expose) => {
  // console.log('initSearchValue', Expose)
  Expose.setValues(searchParams.value)
}

const searchSchema = reactive<FormSchema[]>([
  {
    field: 'name',
    label: '菜单名称',
    component: 'Input'
  },
  {
    field: 'status',
    label: '状态',
    component: 'Select',
    componentProps: {
      options: [
        {
          label: '正常',
          value: 0
        },
        {
          label: '停用',
          value: 1
        }
      ],
      clearable: true
    }
  }
])
const searchRef = ref<ComponentRef<typeof Search>>()

const setSearchParams = (data: any) => {
  searchParams.value = data

  getList()
}

/** 搜索栏重置 */
const resetSearchParams = (data: any) => {
  searchParams.value = data
  searchParams.value.clientType = ElTreeRef.value.getCurrentKey()
  getList()
}

const dialogVisible = ref(false)
const dialogTitle = ref('')

const currentRow = ref()
const actionType = ref('')

const writeRef = ref<ComponentRef<typeof Write>>()

const saveLoading = ref(false)

const action = (row: any, type: string) => {
  // console.profile('action')
  dialogTitle.value = t(type === 'edit' ? 'exampleDemo.edit' : 'exampleDemo.detail')
  actionType.value = type
  currentRow.value = row
  console.log('点击编辑详情', row)
  dialogVisible.value = true
}

const AddAction = () => {
  dialogTitle.value = t('exampleDemo.add')
  currentRow.value = undefined
  dialogVisible.value = true
  actionType.value = ''
}

const save = async () => {
  const write = unref(writeRef)
  const formData = await write?.submit()
  console.log(formData)
  if (formData) {
    saveLoading.value = true
    formData.clientType = ElTreeRef.value!.getCurrentKey()
    delete formData.children
    await sysResourceSaveOrUpdate(formData)
    getList()
    saveLoading.value = false
    dialogVisible.value = false
  }
}
</script>

<template>
  <div class="flex">
    <ContentWrap>
      <ElTree
        ref="ElTreeRef"
        :data="clientTypeTreeData"
        :highlight-current="true"
        :default-expand-all="true"
        node-key="id"
        :props="treeProps"
        @node-click="handleNodeClick"
      />
    </ContentWrap>
    <ContentWrap class="flex-1">
      <Search
        ref="searchRef"
        :schema="searchSchema"
        :operationAdd="true"
        @register="initValue"
        @reset="resetSearchParams"
        @search="setSearchParams"
        @add="AddAction"
      />
      <Table
        :columns="tableColumns"
        default-expand-all
        node-key="id"
        :data="dataList"
        :loading="loading"
        @register="tableRegister"
      />
    </ContentWrap>
  </div>
  <Dialog v-model="dialogVisible" :title="dialogTitle">
    <Write
      v-if="actionType !== 'detail'"
      ref="writeRef"
      :current-row="currentRow"
      :search-params="searchParams"
    />

    <Detail v-if="actionType === 'detail'" :current-row="currentRow" />

    <template #footer>
      <BaseButton
        v-if="actionType !== 'detail'"
        type="primary"
        :loading="saveLoading"
        @click="save"
      >
        {{ t('exampleDemo.save') }}
      </BaseButton>
      <BaseButton @click="dialogVisible = false">{{ t('dialogDemo.close') }}</BaseButton>
    </template>
  </Dialog>
</template>
